package net.thxjj.mobileServer.service.impl;

import com.alibaba.fastjson.JSONObject;
import net.thxjj.mobileServer.dao.CompanyDao;
import net.thxjj.mobileServer.dao.RoomAndPlaceDao;
import net.thxjj.mobileServer.dao.UaaDao;
import net.thxjj.mobileServer.dao.UserDao;
import net.thxjj.mobileServer.entity.*;
import net.thxjj.mobileServer.service.IUaaService;
import net.thxjj.mobileServer.util.JWTUtils;
import net.thxjj.mobileServer.util.JwtUtil;
import net.thxjj.mobileServer.util.ParameterMap;
import net.thxjj.mobileServer.util.SHA;
import net.thxjj.sitermodel.MobileUser;
import net.thxjj.sitermodel.Place;
import net.thxjj.sitermodel.Room;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class UaaService implements IUaaService {
    private Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private UaaDao uaaDao;


    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private RoomAndPlaceDao roomAndPlaceDao;



    @Transactional(rollbackFor=Exception.class)
    @Override
    public HashMap<String, Object> oneKeyCreateAndLogin(ParameterMap pm) {
        try {

           MobileUser mobileUser = uaaDao.getUser(pm.getString("username"),pm.getString("pid"));

           if(mobileUser==null){
               mobileUser = new MobileUser();
               mobileUser.setCreateTime(System.currentTimeMillis());
               mobileUser.setNickname("App Tourlist");
               String pasw = SHA.encryptSHA("1234567890");
               mobileUser.setPassword(pasw);
               mobileUser.setRegisterType(2);
               mobileUser.setUsername(pm.getString("username"));
               mobileUser.setPid(pm.getString("pid"));
               uaaDao.register(mobileUser);

               Place placeBean = new Place();
               placeBean.setName("我的家庭");
               placeBean.setUserId(mobileUser.getUserId());
               placeBean.setCreateTime(System.currentTimeMillis());
               roomAndPlaceDao.insertPlace(placeBean);
               long pl_id = placeBean.getPlaceId();


               List<ParameterMap> list = roomAndPlaceDao.getRoomTemplates();
               List<Room> list1 =new ArrayList<Room>();
               for(ParameterMap parameterMap:list){
                   String roomname = parameterMap.getString("name");
                   Room roomBean = new Room();
                   roomBean.setName(roomname);
                   roomBean.setPlaceId(pl_id);
                   roomBean.setCreateTime(System.currentTimeMillis());
                   roomBean.setType(0);
                   list1.add(roomBean);
               }

               Room roomBean = new Room();
               roomBean.setName("default");
               roomBean.setPlaceId(pl_id);
               roomBean.setCreateTime(System.currentTimeMillis());
               roomBean.setType(1);
               list1.add(roomBean);

               Room roomBean2 = new Room();
               roomBean2.setName("share");
               roomBean2.setPlaceId(pl_id);
               roomBean2.setCreateTime(System.currentTimeMillis());
               roomBean2.setType(2);
               list1.add(roomBean2);

               roomAndPlaceDao.insertRooms(list1);
           }

            ParameterMap parameterMap = new ParameterMap();
            parameterMap.put("user_id",mobileUser.getUserId());
            parameterMap.put("username",mobileUser.getUsername());
            parameterMap.put("pid",mobileUser.getPid());

            //生成jwt
            MobileUser user_token = new MobileUser().setUsername(mobileUser.getUsername()).setUserId(mobileUser.getUserId());
            String access_token = JwtUtil.createToken(user_token);
            String refresh_token = JwtUtil.createRefreshToken(user_token);

            parameterMap.put("access_token",access_token);
            parameterMap.put("refresh_token",refresh_token);

                return ResponseModel.getModel(ResultEnum.SUCCESS, parameterMap);

        }catch(Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("error:"+e.getMessage(), e);
            return ResponseModel.getModel(ResultEnum.ERROR, null);
        }

    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public HashMap<String, Object> emailRegister(ParameterMap pm) {
        try {
            String pasw = pm.getString("password");
            String username = pm.getString("username");
            MobileUser user = new MobileUser();
            user.setCreateTime(System.currentTimeMillis());
            user.setNickname(username);
            user.setEmail(username);
            pasw = SHA.encryptSHA(pasw);
            user.setPassword(pasw);
            user.setRegisterType(0);
            user.setUsername(username);
            user.setPid(pm.getString("pid"));
            uaaDao.register(user);
            uaaDao.updateEmailCodeStatus(pm);

            Place placeBean = new Place();
            placeBean.setName("我的家庭");
            placeBean.setUserId(user.getUserId());
            placeBean.setCreateTime(System.currentTimeMillis());
            roomAndPlaceDao.insertPlace(placeBean);
            long pl_id = placeBean.getPlaceId();


            List<ParameterMap> list = roomAndPlaceDao.getRoomTemplates();
            List<Room> list1 =new ArrayList<Room>();
            for(ParameterMap parameterMap:list){
                String roomname = parameterMap.getString("name");
                Room roomBean = new Room();
                roomBean.setName(roomname);
                roomBean.setPlaceId(pl_id);
                roomBean.setCreateTime(System.currentTimeMillis());
                list1.add(roomBean);
            }
            roomAndPlaceDao.insertRooms(list1);
        }catch(Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("error:"+e.getMessage(), e);
            return ResponseModel.getModel(ResultEnum.ERROR, null);
        }
        return ResponseModel.getModel(ResultEnum.SUCCESS, null);
    }

    @Override
    public HashMap<String, Object> emailReset(ParameterMap pm) {
        try {
            String pasw = pm.getString("password");
            pasw = SHA.encryptSHA(pasw);
            pm.put("password", pasw);
            uaaDao.updatePassword(pm);
            uaaDao.updateEmailCodeStatus(pm);
        }catch(Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("error:"+e.getMessage(), e);
            return ResponseModel.getModel(ResultEnum.ERROR, null);
        }
        return ResponseModel.getModel(ResultEnum.SUCCESS, null);
    }

    @Override
    public boolean isUserExist(String username,String pid) {
        long count = (long)uaaDao.getUserCount(username,pid);

        return count > 0;
    }

    @Override
    public boolean isPidExist(String pid) {
        long count = companyDao.getCompanyCount(pid);
        return count>0;
    }

    @Override
    public long insertEmailVerifyCode(EmailCodeBean emailCodeBean) {
       long id = uaaDao.insertEmailCode(emailCodeBean);
        return id;
    }

    @Override
    public boolean checkRegisterEmailCode(String code, String email, String pid, String sessionId) {
       EmailCodeBean emailCodeBean = uaaDao.getRegisterEmailCode(sessionId,email,code,pid);
       if(emailCodeBean==null)
        return false;
       else {
           if(emailCodeBean.getStatus()==1){
               return false;
           }else{
               long a = System.currentTimeMillis();
               if(a-emailCodeBean.getCreateTime()> Const.EMAIL_CODE_EXPIRE_TIME){
                   return false;
               }else{
                   return true;
               }
           }
       }

    }

    @Override
    public boolean checkResetEmailCode(String code, String email, String pid, String sessionId) {
        EmailCodeBean emailCodeBean = uaaDao.getResetEmailCode(sessionId,email,code,pid);
        if(emailCodeBean==null)
            return false;
        else {

            if(emailCodeBean.getStatus()==1){
                return false;
            }else{
                long a = System.currentTimeMillis();
                if(a-emailCodeBean.getCreateTime()> Const.EMAIL_CODE_EXPIRE_TIME){
                    return false;
                }else{
                    return true;
                }
            }
        }
    }
}
